<template>
  <div class="record-container">
    <!-- 交接班记录表单 -->
    <el-card class="order-card" style="padding-top: 20px" shadow="never">
      <el-form :inline="true" label-position="right" :model="timeOptions" label-width="120px"  size="small" >
        <el-form-item label="交班时间段：" style="margin-right:60px">
          <el-date-picker
            v-model="shiftTimes"
            type="datetimerange"
            unlink-panels
            align="right"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            @change="onChangeShiftTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn-pri-type" style="width: 70px" @click="getShiftRecordList(1)">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 70px" @click="reset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button  @click="onExportExcel" style="width: 70px">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 交接班记录有表格展示 -->
    <el-card class="order-card" shadow="never" :body-style="{ padding: '0'}" style="margin-top: 20px;border: none">
      <el-table v-loading="loading" size="small" :data="tableData.records"  highlight-current-row border  style="width: 100%">
        <!--没有pos收单表格展示-->
        <template v-if="!showPos">
          <el-table-column v-for="(item, index) in tableConfig" :width="item.width" :key="index" :prop="item.prop"  :label="item.label" :align="item.align"></el-table-column>
        </template>
        <!--pos收单表格展示-->
        <template v-else>
          <el-table-column v-for="(item, index) in tableConfig" :width="item.width" :key="index" :prop="item.prop"  :label="item.label" :align="item.align">
            <template slot-scope="scope">
              <div v-if="item.prop === 'dutyName'">{{scope.row.dutyName || 0}}</div>
              <div v-if="item.prop === 'dutyCount'">{{scope.row.dutyCount || 0}}</div>
              <div v-if="item.prop === 'createUser'">{{scope.row.createUser || 0}}</div>
              <div v-if="item.prop === 'period'">{{scope.row.period || 0}}</div>
              <div v-if="item.prop === 'totalGunAmount'">
                <div class="amount_merge">汇总：{{scope.row.totalGunAmount || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appBaseGasDutyRecord.totalGunAmount || 0}}</div>
                <div>POS收单：{{scope.row.posBaseGasDutyRecord.totalGunAmount || 0}}</div>
              </div>
              <div v-if="item.prop === 'totalRealPayAmount'">
                <div class="amount_merge">汇总：{{scope.row.totalRealPayAmount || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appBaseGasDutyRecord.totalRealPayAmount || 0}}</div>
                <div>POS收单：{{scope.row.posBaseGasDutyRecord.totalRealPayAmount || 0}}</div>
              </div>
              <!-- <div v-if="item.prop === 'preferentialAmount'">{{scope.row.preferentialAmount}}</div> -->
              <div v-if="item.prop === 'orderCount'">
                <div class="amount_merge">汇总：{{scope.row.orderCount || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appBaseGasDutyRecord.orderCount || 0}}</div>
                <div>POS收单：{{scope.row.posBaseGasDutyRecord.orderCount || 0}}</div>
              </div>
               <div v-if="item.prop === 'totalLitre'">
                <div class="amount_merge">汇总：{{scope.row.totalLitre || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appBaseGasDutyRecord.totalLitre || 0}}</div>
                <div>POS收单：{{scope.row.posBaseGasDutyRecord.totalLitre || 0}}</div>
              </div>
               <div v-if="item.prop === 'totalRefundAmount'">
                <div class="amount_merge">汇总：{{scope.row.totalRefundAmount || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appBaseGasDutyRecord.totalRefundAmount || 0}}</div>
                <div>POS收单：{{scope.row.posBaseGasDutyRecord.totalRefundAmount || 0}}</div>
              </div>
              <div v-if="item.prop === 'totalSettlement'">
                <div class="amount_merge">汇总：{{scope.row.totalSettlement || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appBaseGasDutyRecord.totalSettlement || 0}}</div>
                <div>POS收单：{{scope.row.posBaseGasDutyRecord.totalSettlement || 0}}</div>
              </div>
              <div v-if="item.prop === 'totalRealSettlement'">
                <div class="amount_merge">汇总：{{scope.row.totalRealSettlement || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appBaseGasDutyRecord.totalRealSettlement || 0}}</div>
                <div>POS收单：{{scope.row.posBaseGasDutyRecord.totalRealSettlement || 0}}</div>
              </div>
            </template>
          </el-table-column>
        </template>
        <el-table-column width="240" label="操作" fixed="right"  align='center'>
          <template slot-scope="scope">
            <el-button-group>
              <el-button class="btn-style primary" size="mini" @click="showDetail(scope.row.id)">详情</el-button>
              <el-button lass="btn-style" size="mini" @click="showDoc(scope.row.id)">补打小票</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageOptions.pageIndex"
        :page-sizes="pageSizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total"
        class="tablePagination">
      </el-pagination>
    </el-card>
    <!-- 补打小票弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="isShowTicket"
      width="30%"
      center>
      <div style="width: 100%;text-align: center">确认补打小票？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowTicket = false">取 消</el-button>
        <el-button class="btn-pri-type" type="primary" @click="handleTicket">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
// import MerTable from '@/components/work/MerTable'
import { getChangeAndShiftTimeList, exportHandoverList, makeUpTicket } from '@/api/handover'
import { showRealAmount } from '@/api/order'
import { exportSearchList } from '@/utils/listTools'

// 表格参数配置
let tableConfig = [
  { label: '班次', prop: 'dutyName', width: 100, align: 'center' },
  { label: '班次时间段', prop: 'period', width: 200, align: 'center'},
  { label: '加油金额（元）', prop: 'totalGunAmount', width: 136, align: 'center' },
  { label: '实付金额（元）', prop: 'totalRealPayAmount', width: 136, align: 'center' }, // 根据接口判断是否展示的
  // { label: '优惠金额（元）', prop: 'preferentialAmount', width: 136, align: 'center' },
  { label: '加油笔数', prop: 'orderCount', width: 136, align: 'center' },
  { label: '加油升数', prop: 'totalLitre', width: 136, align: 'center' },
  { label: '退款金额（元）', prop: 'totalRefundAmount', width: 156, align: 'center' },
  { label: '应结算金额（元）', prop: 'totalSettlement', width: 136, align: 'center'}, // 根据接口判断是否展示的
  { label: '交班人姓名', prop: 'createUser', width: 156, align: 'center' },
  { label: '实际结算金额（元）', prop: 'totalRealSettlement', width: 136, align: 'center' } // 根据接口判断是否展示的
]

export default {
  name: 'handover_handoverRecord',
  components:{
    // MerTable
  },
  data () {
    return {
      showPos: true, // 是否有pos收单
      tableData: { // 表格
        records: [],    //列表数据
        total: 0        //总条数 
      },
      tableConfig,
      dutyId: '', // id
      isShowTicket: false,
      loading: false,
      saveOptions: {},
      timeOptions: {
        dutyStartTime: '', // 交班开始时间
        dutyEndTime: ''  // 交班结束时间
      },
      pageOptions: {
        pageIndex: 1,
        pageSize: 20
      },
      pageSizes: [20],
      shiftTimes: []
    }
  },
  async mounted () {
    this.resetDate()
    this.saveOptions = { ...this.timeOptions }
    this.getShiftRecordList(0)
    // 是否在表格里面展示totalRealPayAmount 实付金额（元）字段
    try {
      const {code, result} = await showRealAmount()
      if (code !== 200) return
      if (!result) {
        const index = this.tableConfig.findIndex(item => item.prop === 'totalRealPayAmount')
        if (index !== -1) this.tableConfig.splice(index, 1)
      }
    } catch (error) {
      console.log(error)
    }
  },
  methods: {
    reset () {
      this.resetDate()
      this.pageOptions.pageIndex = 1
      this.pageOptions.pageSize = 20
      this.getShiftRecordList(0)
    },
    judTime () {
      const { dutyStartTime, dutyEndTime } = this.timeOptions
      let changeoverTime1 = moment(dutyStartTime).valueOf() || ''
      let shiftTime1 = moment(dutyEndTime).valueOf() || ''
      if (!shiftTime1 || !changeoverTime1) {
        this.$message.error('请选择时间范围')
        return false
      }
      if (shiftTime1 > +new Date()) {
        this.$message.error('交班时间段必须小于或等于系统当前时间')
        return false
      }
      if (shiftTime1 < changeoverTime1) {
        this.$message.error('交班时间需要大于或等于接班时间')
        return false
      }
      return true
    },
    resetDate () {
      let date = new Date()
      this.shiftTimes = [new Date(date.getTime() - 3600 * 1000 * 24 * 30),date]
      this.timeOptions.dutyStartTime = moment(date.getTime() - 3600 * 1000 * 24 * 30).format("YYYY-MM-DD HH:mm:ss")
      this.timeOptions.dutyEndTime = moment().format("YYYY-MM-DD HH:mm:ss")
    },
    onChangeShiftTime (val) { // 选择交班时间段
      if (val) {
        this.timeOptions.dutyStartTime = val[0]
        this.timeOptions.dutyEndTime = val[1]
      } else {
        this.timeOptions.dutyStartTime = ''
        this.timeOptions.dutyEndTime = ''
      }
    },
    async getShiftRecordList (type, change = false) { // （点击）获取交接班记录
      if (change) {
        this.timeOptions = { ...this.saveOptions }
        let { dutyStartTime, dutyEndTime } = this.saveOptions
        this.shiftTimes = [dutyStartTime, dutyEndTime]
      }
      if (type) {
        if(!this.judTime()) return
        this.pageOptions.pageIndex = 1
        this.pageOptions.pageSize = 20
      }
      this.loading = true
      let params = {...this.timeOptions, ...this.pageOptions}
      try {
        const { code, result, totalRow = 0 } = await getChangeAndShiftTimeList(params)
        if (code !== 200) return
        this.showPos = result.showPos  // 判断是否展示pos收单信息
        if (!result.isShowSum) { // 是否展示结算金额，操作列表两个字段是否展示
          const besArr = ['totalSettlement', 'totalRealSettlement']
          this.tableConfig = this.tableConfig.filter(item => {
            return !besArr.includes(item.prop)
          })
        }
        this.tableData.records = result.records.map(item => {
          item.period = item.dutyStartTime + ' ~ ' + item.dutyEndTime
          return item
        })
        this.tableData.total = totalRow
        console.log(this.tableData)
        if (type) this.saveOptions = { ...this.timeOptions }
      } catch (error) {
        console.log(error.message)
      } finally {
        this.loading = false
      }
    },
    async onExportExcel () { // 导出
      let length = this.tableData.records.length
      if (!length) {
        this.$message.error('导出excel为空，不能导出')
        return
      }
      try {
        const { code, result = {} }= await exportHandoverList(this.saveOptions)
        if (code !== 200) return
        exportSearchList(result.file, result.fileName)
      } catch (error) {
        console.log(error.message)
      }
    },
    showDetail (id) { // 展示详情
      this.$router.push({ path: '/handover/handoverDetail', query: { id } })
    },
    handleSizeChange (val) { // 分页改变时
      console.log(val)
    },
    handleCurrentChange (val) { // 翻页
      this.pageOptions.pageIndex = val
      this.getShiftRecordList(0, true)
    },
    showDoc (dutyId) { // 补打小票
      this.dutyId = dutyId
      this.isShowTicket = true
    },
    async handleTicket () {
      try {
        const { code } = await makeUpTicket({ dutyId: this.dutyId })
        if (code !== 200) return
        this.$message.success('补打小票成功')
      } catch (error) {
        console.log(error.message)
      } finally {
        this.isShowTicket = false
        this.getShiftRecordList(0, true)
      }
    }   
  }
}
</script>

<style lang="less" scoped>
.record-container{
  padding: 40px 10px;
  min-width: 80%;
  min-height: 500px;
  box-sizing: border-box;
  background-color: #F8F9FD;
}
.block{
  margin: 20px 10px;
  text-align: center;
}
.btn-pri-type{
  background: #4B7EFE; 
  border: none;
}
.btn-style{
  background: transparent;
  &.primary{
    margin-right: 15px;
    margin-left: 5px;
    min-width: 80px;
  }
}
.amount_merge{
  border-bottom: 1px solid #EAEEF4;
}
.tablePagination{
  margin: 15px 0;
  float: right;
}
</style>
